<%@ path=${filename}%>

<%
	JsonEntity(Item)
	{
		rstring(name);
		nstring(tabid);
		nstring(title);
		nstring(filter);
		nstring(remark);
		nstring(statetime);
		rint(enabled);
		rint(position);
		rint(querytype);
	};

	JsonEntity(Param)
	{
		nstring(name);
		nstring(dbid);
		nstring(tabid);
		narray(Item, list);
	};

	Param param;
	
	checkLogin();

	param.fromString(request->getDataString());

	if (param.list.empty())
	{
		JsonEntity(Item)
		{
			rstring(dbid);
			rstring(name);
		};

		Item item;

		param_string(tabid);

		webx::GetDBConnect()->select(item, "SELECT DBID,NAME FROM T_XG_TABETC WHERE ID=?",  param.tabid = tabid);

		param.dbid = item.dbid;
		param.name = item.name;

		if (param.dbid == "$system" || param.dbid == "$(system)" || param.dbid == "${system}")
		{
			param.dbid.clear();
		}
	}
	else
	{
		int res = XG_OK;
		string datetime = DateTime::ToString();
		sp<DBConnect> dbconn = webx::GetDBConnect();

		dbconn->begin();

		dbconn->execute("DELETE FROM T_XG_TABCOLS WHERE tabid=?", param.tabid);

		for (auto& item : param.list.getList())
		{
			item->tabid = param.tabid;
			item->statetime = datetime;
	
			if (dbconn->insert(*item, "T_XG_TABCOLS") < 0)
			{
				dbconn->rollback();

				return simpleResponse(XG_SYSERR);
			}
		}

		dbconn->commit();

		return simpleResponse(res);
	}
%>

<style>
#RecordColumnDiv{
	height: 100%;
	background: #FFF;
	overflow-y: auto;
}
#RecordColumnDiv option{
	color: #EEE;
	background: #000;
}
#RecordColumnDiv tr:first-child{
	top: 0px;
	z-index: 1;
	position: sticky;
}
</style>

<div style='width:950px;height:73vh;padding-bottom:10px'>
	<div id='RecordColumnDiv' class='HiddenScrollbar'></div>
</div>

<script>
{
    let checkmap = new Map();

	let querytypelist = [
		"<option value='0'>不用查询</option>",
		"<option value='1'>完全匹配</option>",
		"<option value='2'>前缀匹配</option>",
		"<option value='3'>模糊匹配</option>",
		"<option value='4'>日期范围</option>",
		"<option value='5'>时间范围</option>"
	];

    getVue('RecordColumnDiv');

	getHttpResult('/getcolumnlist', {flag: 'A', tabid: '<%=param.tabid%>'}, function(data){
		if (data.code > 0){
			data.list.forEach(item => {
				checkmap.set(item.name, item);
			});
		}
	});

	let vmdata = {
		title: {
			name: '字段',
			type: '类型',
			visable: '展示',
			querytype: '查询条件',
			title: '列表名称',
			filter: '过滤条件'
		},
		check: function(data){
            data.list.sort(function(a, b){
                let m = checkmap.get(a.name);
                let n = checkmap.get(b.name);
                if (m == null) m = {position: 10000};
                if (n == null) n = {position: 10000};
                return m.position - n.position;
            });

			function translate(str){
				return str ? str.replaceAll('<', '&lt;').replaceAll('>', '&gt;').replaceAll('\'', '&#39;').replaceAll('\"', '&quot;') : str;
			}

			data.list.forEach(item => {
				let data = checkmap.get(item.name);
				let option = querytypelist.join("");
				if (data == null) data = {title: '', filter: '', enabled: 0, querytype: 0};
				item['title'] = "<input class='TextField' type='text' size='16' maxlength='24' value='" + translate(data.title) + "'/>";
				item['filter'] = "<input class='TextField' type='text' size='64' maxlength='512' value='" + translate(data.filter) + "'/>";
				item['visable'] = "<input type='checkbox' style='top:2px;position:relative' " + (data.enabled > 0 ? 'checked' : '') + "/>";
				item['querytype'] = "<select class='TextSelect'>" +  option.replace("value='" + data.querytype + "'", "value='" + data.querytype + "' selected") + "</select>";
			});
		},
		pagesize: 10000
	};

	let view = $('#RecordColumnDiv').hide();
	let listview = new RecordListView(view, '/exportentity', vmdata, function(){
		return {dbid: '<%=param.dbid%>', name: '<%=param.name%>', format: 'list'};
	}, true);

	let menubox = new ContextMenu(['上移', '下移'], function(text, elem){
		let item = $(getContextMenuAttach());
		if (text == '上移'){
			if (item.prev().prev().length > 0){
				item.prev().insertAfter(item);
			}
		}
		else{
			item.next().insertBefore(item);
		}
	}, view);

	setTimeout(function(){
		let idx = 0;
		view.find('tr').each(function(){
			if (idx++ > 0){
				$(this).find('td').css('background', '#FFF').css('padding', '3px');
				menubox.bind(this);
			}
			else{
				$(this).find('td').css('padding', '3px');
			}
		});
		view.show();
	}, 100);

	$('#XG_MSGBOX_DIV_CONFIRM_ID').click(function(){
		let idx = 0;
		let arr = [];
		view.find('tr').each(function(){
			if (idx++ > 0){
				let item = {'position': idx};
				let cols = $(this).children();
				item['name'] = $(cols[1]).text();
				item['type'] = $(cols[2]).text();
				item['enabled'] = $(cols[3]).children()[0].checked ? 2 : 0;
				item['querytype'] = $(cols[4]).children().val();
				item['title'] = $(cols[5]).children().val();
				item['filter'] = $(cols[6]).children().val();
				arr.push(item);
			}
		});
		getHttpResult('/${filename}', {tabid: '<%=param.tabid%>', list: arr}, function(data){
			if (data.code == XG_TIMEOUT){
				sessionTimeout();
			}
			else if (data.code == XG_AUTHFAIL){
				showNoAccessToast();
			}
			else if (data.code < 0){
				showToast('保存字段配置失败');
			}
			else{
				$recordvmdata.reload();
				showToast('保存字段配置成功');
			}
		}, false, true);
	});
}
</script>